package com.fengke.csc.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fengke.csc.config.HostConfig;
import com.fengke.service.vo.AgentProfileVO;
import com.fengke.util.Constants;

/**
 * Servlet Filter implementation class PermissionFilter
 */
public class PermissionFilter implements Filter {

    /**
     * Default constructor. 
     */
    public PermissionFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain chain) throws IOException, ServletException {
		request1.setCharacterEncoding("UTF-8");
		HttpServletRequest request = (HttpServletRequest) request1;
		HttpServletResponse response = (HttpServletResponse) response1;
		AgentProfileVO agentProfileVO = (AgentProfileVO) request.getSession().getAttribute(Constants.SessionProfileName.CSC_PROFILE_NAME);
		HostConfig hostConfig = (HostConfig) request.getSession().getServletContext().getAttribute("hostConfig");
		if(agentProfileVO == null) {
			// 未登录，校验是否为登录流程页面
			String requestURI = request.getRequestURI();
			if(!requestURI.contains("/sso/") && !requestURI.contains("/cache/")) {
				// 未登录，非登录相关链接，强制跳转至登录页面
				// 拼接backURL
				StringBuilder params = new StringBuilder();
				@SuppressWarnings("unchecked")
				Enumeration<String> ee =request.getParameterNames();
				while(ee.hasMoreElements()){
					String name = (String)ee.nextElement();
					String value =(String)request.getParameter(name);
					if(params.length() > 0) {
						params.append("&");
					}
					params.append(name).append("=").append(value);
				}
				request.getSession().setAttribute(Constants.BACK_URL, request.getRequestURL() + ((params != null && params.length() > 0) ? ("?" + params.toString()) : ""));
				
				response.sendRedirect(hostConfig.getPortalHost() + hostConfig.getLoginFormURL());
				return;
			}
		}
		
		// TODO 权限校验
		
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
